<?php
/**
 * tpshop
 * ============================================================================
 * 版权所有 2015-2027 深圳搜豹网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.tp-shop.cn
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * Author: IT宇宙人
 * Date: 2015-09-09
 */

namespace Home\Logic;

use Think\Model\RelationModel;
use Think\Page;
use \JPush\Client as Jpush;

/**
 * 逻辑定义
 * Class CatsLogic
 * @package Home\Logic
 */
class UserSosLogic extends RelationModel {

    /**
     * @param $user_id
     * @return array
     * 报警接口
     * 先添加报警数据
     * 在查找好友信息,每个好友信息发推送
     */
    public function to_sos($user_id, $location, $add_res) {
        //检查参数
        if (!$user_id || !$location) {
            return toJson(-1, "The parameter is incorrect");
        }
        $user = M('user')->where("user_id='{$user_id}'")->find();
        if (!$user) {
            return toJson(-1, "User_id error");
        }
        $sos_time = time();

        $userContact = new \Home\Logic\UserContactLogic();
        $data = $userContact->getContact_ok($user_id);
        if (empty($data)) {
            return toJson(-1, "You do not have friends, can not alarm!");
        }
        //添加报警数据
        $sosId = M('user_sos')->add(array("user_id" => $user_id, "help_text" => $user["help_text"], "location" => $location, "sos_time" => $sos_time));

        //发送短信的用户数组
        $msg_array = array();
        for ($i = 0; $i < count($data); $i++) {
            $pushArray = array("sos_id" => $sosId, "push_time" => time(), "receiver_id" => $data[$i]['user_List']['user_id']);
            $push_id = M('push')->add($pushArray);
            /**
             * 在这里推送
             * 推送没接
             */
            M('push_recording')->add(array("user_id" => $user_id, "push_type" => "bj", "user_id_push" => $data[$i]['user_List']['user_id'], "push_id" => $push_id, 'sos_time' => $sos_time, 'sos_id' => $sosId, 'status' => 'loading'));
            $client = new Jpush();
            $client->push()
                ->setPlatform('all')
                ->addAlias($data[$i]['user_List']['user_id'])
                ->iosNotification($user['last_name'] . $user['first_name'] . ':' . $user["help_text"],
                    array('content-available' => 'true', 'sound' => 'Alarm.wav', 'extras' => array('user' => $user, 'push_id' => $push_id, 'type' => 'bj', 'user_sos' => $user["help_text"], 'time' => $sos_time, 'sosId' => $sosId)))
                ->options(array(
                    "apns_production" => true  //true表示发送到生产环境(默认值)，false为开发环境
                ))
                ->send();
            $msg_array[$data[$i]['user_List']['user_phone']] = $user['last_name'] . $user['first_name'] . ':' . $user["help_text"] . ' address: ' . $add_res;
//            $user_index->send_Msg($data[$i]['user_List']['user_phone'], $user['last_name'] . $user['first_name'] . ':' . $user["help_text"] . ' address: ' . $add_res);
        }
        $user_index = new \Home\Logic\UserLogic();
        $user_index->send_Msg($msg_array);

        return toJson(1, $sosId);
    }

    //根据sosid查sos表
    public function getLocationBySosId($sos_id) {
        return M('user_sos')->where("sos_id='{$sos_id}'")->find();
    }

    //接受报警
    public function Accept_Sos($user_id, $push_id) {
        //检查参数
        if (!$user_id || !$push_id) {
            return toJson(-1, "Parameters are available");
        }
        $data = M('push')->where("push_id='{$push_id}' and receiver_id='{$user_id}'")->find();
        if (!$data) {
            return toJson(-1, "Parameter error, could not find the user's push information");
        }
        $data["receiver_time"] = time();
        $data["is_response"] = "ok";
        M('push')->where("push_id='{$push_id}' and receiver_id='{$user_id}'")->save($data);
        return toJson(1, $this->getLocationBySosId($data["sos_id"]));
    }

    //上传定位
    public function set_Location($sos_id, $location) {
        if (!$sos_id || !$location) {
            return toJson(-1, "Parameters are available");
        }
        $data = M('user_sos')->where("sos_id='{$sos_id}'")->find();
        if (!$data) {
            return toJson(-1, "Sos_id error");
        }
        $data["location"] = $location;
        M('user_sos')->where("sos_id='{$sos_id}'")->save($data);
        return toJson(1, "ok");
    }

    //查询我报警的记录 返回推送所有的好友
    public function query_SosByPush($user_id) {
        if (!$user_id) {
            return toJson(-1, "Parameters are available");
        }
        $dataArray = M('user_sos')->where("user_id='{$user_id}'")->order("sos_time desc")->select();
        for ($i = 0; $i < count($dataArray); $i++) {
            $pushArray = M('push')->where("sos_id='{$dataArray[$i]["sos_id"]}'")->select();
            $userArray = array();
            for ($j = 0; $j < count($pushArray); $j++) {
                $userArray[$j] = M('user')->where("user_id='{$pushArray[$j]["receiver_id"]}'")->find();
            }
            $dataArray[$i]["userArray"] = $userArray;
        }
        return toJson(1, $dataArray);
    }

    //删除某个我报警的记录
    public function delete_SosByPush($sos_id) {
        if (!$sos_id) {
            return toJson(-1, "Parameters are available");
        }
        M('user_sos')->where("sos_id='{$sos_id}'")->delete();
        return toJson(1, "ok");
    }

    //查询别人向我报警的记录
    public function query_UserByPush($user_id) {
        if (!$user_id) {
            return toJson(-1, "Parameters are available");
        }
        $pushArray = $this->getPushArray($user_id);
        $num = 0;
        for ($i = 0; $i < count($pushArray); $i++) {
            $sos = M('user_sos')->where("sos_id='{$pushArray[$i]["sos_id"]}'")->find();
            if ($sos) {
                $user_sosArray[$num] = $sos;
                $user = M('user')->where("user_id='{$sos["user_id"]}'")->find();
                $user_sosArray[$num]["user"] = $user;
                $num++;
            }
        }

        $dataArray = array();
        $res = count($user_sosArray);
        $o = 0;
        for ($i = 0; $i < $res; $i++) {
            if (!$user_sosArray[$i]) {
                continue;
            }
            $dataArray[][] = $user_sosArray[$i];
            for ($j = $i + 1; $j < $res; $j++) {
                if ($user_sosArray[$i]["user_id"] == $user_sosArray[$j]["user_id"]) {
                    $dataArray[$o][] = $user_sosArray[$j];
                    unset($user_sosArray[array_search($user_sosArray[$j], $user_sosArray)]);
                }
            }
            $o++;
        }
        return toJson(1, $dataArray);

    }

    /**
     * 查询该用户推送信息
     * @param $user_id
     * @return array
     */
    public function query_UserPush($user_id) {
        if (!$user_id) {
            return toJson(-1, "Missing parameters!");
        }
        $userPash_array = M('push_recording')->where("user_id_push='{$user_id}' and status='loading'")->select();
        for ($i = 0; $i < count($userPash_array); $i++) {
            $userPash_array[$i]['user'] = M('user')->where("user_id='{$userPash_array[$i]['user_id']}'")->find();
            $data = $userPash_array[$i];
            $data["status"] = "ok";
            M('push_recording')->where("push_recording_id='{$data["push_recording_id"]}'")->save($data);
        }
        return toJson(1, $userPash_array);
    }

    /**
     * 查询该用户邀请他的好友信息
     * @param $user_id
     * @return array
     */
    public function query_FriendList($user_id) {
        if (!$user_id) {
            return toJson(-1, "Missing parameters!");
        }
        $user_array = M('user_contact')->where("binding_id='{$user_id}' and state='loading'")->select();
        for ($i = 0; $i < count($user_array); $i++) {
            $user_array[$i]['user'] = M('user')->where("user_id='{$user_array[$i]['user_id']}'")->find();
        }
        return toJson(1, $user_array);
    }

    /**
     * 删除莫某个人向我报警的记录
     */
    public function delete_UserByPush($user_id, $delete_user_id) {
        if (!$user_id || !$delete_user_id) {
            return toJson(-1, "Parameters are available");
        }

        $pushArray = $this->getPushArray($user_id);
        for ($i = 0; $i < count($pushArray); $i++) {
            $sos = M('user_sos')->where("sos_id='{$pushArray[$i]["sos_id"]}'")->find();
            if ($delete_user_id == $sos["user_id"]) {
                M('push')->where("push_id='{$pushArray[$i]["push_id"]}'")->delete();
            }
        }
        return toJson(1, "ok");
    }

    public function getPushArray($user_id) {
        return M('push')->where("receiver_id='{$user_id}'")->order("push_time desc")->select();
    }


}